<template>
  <el-row style="padding: 5px">
    <el-row>
      <el-card>
        <el-form :inline="true" :model="this.codeParams" class="" size="small">
          <el-form-item label="产品">
            <el-select v-model="codeParams.sellproId" placeholder="请选择产品">
              <el-option v-for="item in sellproOption"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="版本">
              <el-select v-model="codeParams.versionId" placeholder="请选择版本">
                <el-option label="20240201" value="shanghai"></el-option>
                <el-option label="20240203" value="beijing"></el-option>
                <el-option label="20240204" value="beijing"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="溯源码">
            <el-input v-model="codeParams.traceCode" placeholder="请输入溯源码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="selectCodeData">搜索</el-button>
            <el-button type="" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" plain icon="el-icon-plus" @click="addCodeData(1)" v-hasPermi="['agriculture:code:generateCode']">生成溯源码</el-button>
            <button_disbable></button_disbable>
<!--            <el-button type="warning" plain icon="el-icon-download">导出</el-button>-->
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
    <el-row style="margin-top: 5px">
      <el-card>
        <el-button type="danger"  icon="el-icon-delete" size="mini" @click="deleteCode" plain>批量删除</el-button>
        <el-table :data="tableData.slice((currentPage -1) *pageSize,currentPage*pageSize)" border style="width: 100% ;margin-top: 10px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" prop="sellproName" label="溯源产品" width="150px"></el-table-column>
          <el-table-column align="center" prop="versionCode" label="溯源版本" width="150px"></el-table-column>
          <el-table-column align="center" prop="traceCode" label="溯源码"></el-table-column>
          <el-table-column align="center" prop="traceUrl" label="溯源连接">
            <template slot-scope="scope">
              <div @click="handleQrCodeClick(scope.row.traceUrl)">
                <vue-qr :text="scope.row.traceUrl" :margin="0" colorDark="#f67b29" colorLight="#fff" :logoScale="0.3" :size="30">
                </vue-qr>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态" width="100px">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success">可用</el-tag>
                <el-tag v-else type="danger">不可用</el-tag>
              </template>
          </el-table-column>
          <el-table-column align="center" prop="" label="操作" width="150px">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" class="mini_Button" @click="goToRecordPage()">查看溯源记录</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin: 20px 0; float: right"
          :current-page.sync="currentPage"
          background
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="this.tableData.length">
        </el-pagination>
      </el-card>
    </el-row>
    <el-dialog :visible.sync="dialogVisible" width="15%" :custom-class="this.dialogStyle" >
      <vue-qr :text="this.showQRcode"
              :margin="0"
              colorDark="#f67b29"
              colorLight="#fff"
              :logoScale="0.3"
              :size="200">
      </vue-qr>
    </el-dialog>

    <el-dialog  :visible.sync="this.dialog" width="30%">
      <template v-slot:title>
        <div style="color: black;font-weight:1000; font-size: 20px;">{{dialogTitle}}</div>
      </template>
      <el-form :model="this.addCode">
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>溯源产品</template>
          <el-select v-model="addCode.sellproId" placeholder="请选择溯源产品" style="width:70%" @change="selectVersion">
            <el-option v-for="item in sellproOption"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>溯源版本</template>
          <el-select v-model="addCode.versionId" placeholder="请选择溯源产品" style="width:70%" :no-data-text="ondataText">
            <el-option v-for="item in versionOption"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>数量</template>
          <el-input-number v-model="addCode.codeNum" placeholder="请选择数量" style="width:70%;margin-left: 28px" controls-position="right" :max="10000"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog=false">取 消</el-button>
        <el-button type="primary" @click="handleButtonClick">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "@/views/iot/template/index.vue";
import {delCode, generateCode, listCode} from "@/api/agriculture/code";
import vueQr from 'vue-qr'
import {listSellpro} from "@/api/agriculture/sellpro";
import {listVersion} from "@/api/agriculture/version";
import Button_disbable from "@/views/agriculture/buttonDis/button_disbable.vue";
import Version from "@/views/agriculture/version/index.vue";

export default {
  computed: {
    Version() {
      return Version
    }
  },
  components: {Button_disbable, Template,vueQr},
  data() {
    const initialAddData={
     sellproId:'',
     versionId:'',
      codeNum:'',
    }
    return {
      addCode:{...initialAddData},
      initialAddData,
      dialogTitle:'',
      dialog:false,
      currentPage:1,
      pageSize:10,
      dialogStyle: {
        backgroundColor: 'rgba(255, 255, 255, 0.5)',
        boxShadow: 'none'
      },
      dialogVisible: false,
      formInline: {
        user: '',
        region: ''
      },
      drawer:false,
      showQRcode:'',
      codeParams:{
        traceCode:'',
        versionId:'',
        sellproId:'',
      },
      versionParams:{
        sellproId:'',
        versionCode:'',
        expireDate:'',
      },
      sellproParams:{
        sellproName:'',
        sellproArea:'',
        sellproWeight:'',
        sellproGuige:'',
        sellproImg:'',
        germplasmId:'',
        batchId:'',
        landId:'',
        deviceId:'',
        cameraId:'',
        staffId:'',
        shopId:'',
        h5Url:'',
        status:'',
        orderNum:'',
      },
      addOrUpdate:'',
      sellproOption:'',
      versionOption:'',
      selectionData:[],
      tableData: [],
      ondataText:'请先选择产品',
      generate:{
        versionId:'',
        codeNum:'',
      },
      requiredFields:{  sellproId:'请选择产品',versionId:'请选择版本',codeNum:'请选择数量'  }
    }
  },
  async mounted() {
    await this.getCodeData()
  },
  methods:{
    async selectVersion(){
      this.versionParams.sellproId=this.addCode.sellproId
      const row1 = await listVersion(this.versionParams)
      if(row1.total>0)
      {
        this.versionOption = row1.rows.map(item => ({
          value: item.versionId,
          label: item.versionCode
        }));
      } else{
        this.ondataText='当前产品无溯源版本，请先生成溯源版本！'
      }
    },
    // 获取产品
    async getCodeData()
    {
      const row = await  listVersion(this.versionParams)
      const row1 = await listCode(this.codeParams)
      const row2 = await listSellpro(this.sellproParams)
      this.sellproOption = row2.rows.map( item =>({
        value:item.sellproId,
        label:item.sellproName
      }))
      this.tableData =row1.rows.map(item1=>{
        const findVersion =row.rows.find(item3 => item1.sellproId === item3.sellproId)
        const findSellpro =row2.rows.find(item2 => item1.sellproId === item2.sellproId)
        return {
          ...item1,
          sellproName:findSellpro.sellproName,
          versionCode:findVersion.versionCode
        }
      });
    },
    deleteCode()
    {
      this.$confirm('确认删除？')
        .then(async _ => {
          try {
            delCode(this.selectionData)
            this.openMessage('success', '删除成功！');
            await this.getCodeData()
          } catch (error) {
            console.log("溯源码删除错误:", error)
            this.openMessage('error', '删除失败！');
          }
        }).catch(_ => {
        return
      });
    },
    // 对话框确定按钮选择监听修改或新增
    handleButtonClick() {
      if (this.addOrUpdate === 1) {
        // this.updateRecordData(this.addRecord,2)
      } else {
        this.addCodeData(2);
      }
    },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
    // 新增
    async addCodeData(buttonId)
    {
      if(buttonId == 1) {this.addCode= { ...this.initialAddData };this.dialogTitle ='生成溯源码';this.dialog= true; this.addOrUpdate = 0}
      else if(buttonId == 2) {
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addCode[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
          this.generate.versionId=this.addCode.versionId
          this.generate.codeNum=this.addCode.codeNum
        }
        try {
          await generateCode(this.generate)
          this.openMessage('success', '添加成功！');
          await this.getCodeData()
          this.addCode={...this.initialAddData}
          this.dialog = false
        } catch (error) {
          console.error('添加溯源码错误:', error);
          this.openMessage('error', '添加失败！');
        }
      }
    },
    // 查询
    async selectCodeData(){
      await this.getCodeData()
    },
    // 重置
    async resetForm() {
      this.codeParams.sellproId = '',
      this.codeParams.traceCode = '',
      this.codeParams.versionId = ''
      await this.getCodeData()
    },
    // 放大二维码
    handleQrCodeClick(row)
    {
      this.dialogVisible=true;
      this.showQRcode=row;
    },
    // 批量选中
    handleSelectionChange(selection){
      this.selectionData=selection.map(item =>item.codeId)
    },
    // 跳转页面
    goToRecordPage()
    {
      this.$router.push('/trace/record');
    },

  }
}
</script>
<style scoped>
.mini_Button{
  font-size:12px;
  padding: 4px 9px
}
</style>

